import React, { useState } from 'react';
import { Form, Input, Button, Typography, message, Card, Select, Upload } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, UploadOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { useNavigate, Link } from 'react-router-dom';
import api from '../services/api';
import type { UploadProps } from 'antd';
import { RcFile, UploadChangeParam, UploadFile } from 'antd/es/upload/interface';

const { Title } = Typography;
const { Option } = Select;

const RegisterContainer = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
`;

const RegisterFormWrapper = styled.div`
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
`;

const StyledButton = styled(Button)`
  width: 100%;
`;

const RegisterPage: React.FC = () => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [fileList, setFileList] = useState<UploadFile[]>([]);

    const handleFileChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setFileList(newFileList.slice(-1));
    };

    const onFinish = async (values: any) => {
        setLoading(true);
        try {
            const submissionData = { ...values };

            let avatarUrl = null;
            if (fileList.length > 0 && fileList[0].originFileObj) {
                const file = fileList[0].originFileObj as RcFile;
                const formData = new FormData();
                formData.append('avatar', file);

                try {
                    const uploadResponse = await api.upload.uploadAvatar(formData);

                    if (uploadResponse.success && uploadResponse.url) {
                        avatarUrl = uploadResponse.url;
                        // message.success('头像上传成功！');   
                    } else {
                        message.error(uploadResponse.message || '头像上传失败');
                        setLoading(false);
                        return;
                    }
                } catch (uploadError) {
                    console.error('Avatar upload failed:', uploadError);
                    message.error('头像上传失败');
                    setLoading(false);
                    return;
                }
            } else if (fileList.length === 0) {
                avatarUrl = null;
            }

            if (avatarUrl !== null) {
                submissionData.avatar = avatarUrl;
            } else {
                delete submissionData.avatar;
            }

            const response = await api.auth.register(submissionData.username, submissionData.email, submissionData.password, submissionData.gender, submissionData.avatar);

            if (response.success) {
                message.success('注册成功！请登录。');
                navigate('/login');
            } else {
                message.error(response.message || '注册失败');
            }
        } catch (error) {
            console.error('Registration error:', error);
            message.error('注册失败');
        } finally {
            setLoading(false);
        }
    };

    return (
        <RegisterContainer>
            <RegisterFormWrapper>
                <Title level={2} style={{ textAlign: 'center', marginBottom: 32 }}>
                    用户注册
                </Title>
                <Form
                    name="register"
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                >
                    <Form.Item label="头像">
                        <Upload
                            listType="picture-card"
                            fileList={fileList}
                            onChange={handleFileChange}
                            beforeUpload={() => false}
                            maxCount={1}
                        >
                            {fileList.length === 0 && (
                                <div>
                                    <UploadOutlined />
                                    <div style={{ marginTop: 8 }}>上传头像</div>
                                </div>
                            )}
                        </Upload>
                    </Form.Item>

                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: '请输入用户名' }]}
                    >
                        <Input prefix={<UserOutlined />} placeholder="用户名" />
                    </Form.Item>

                    <Form.Item
                        name="email"
                        rules={[
                            { required: true, message: '请输入邮箱' },
                            { type: 'email', message: '请输入有效的邮箱地址' },
                        ]}
                    >
                        <Input prefix={<MailOutlined />} placeholder="邮箱" />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input.Password prefix={<LockOutlined />} placeholder="密码" />
                    </Form.Item>

                    <Form.Item
                        name="gender"
                        label="性别"
                        rules={[{ required: true, message: '请选择性别!' }]}
                    >
                        <Select placeholder="请选择性别">
                            <Option value="male">男</Option>
                            <Option value="female">女</Option>
                            <Option value="other">其他</Option>
                        </Select>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={loading} style={{ width: '100%' }}>
                            注册
                        </Button>
                    </Form.Item>

                    <div style={{ textAlign: 'center' }}>
                        已有账号？ <Link to="/login">立即登录</Link>
                    </div>

                </Form>
            </RegisterFormWrapper>
        </RegisterContainer>
    );
};

export default RegisterPage; 